<script lang="ts" setup>
import { reactive, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { Modal as AntModal, Button, Divider, Input, message, Select, Space, Table, TableColumn } from 'ant-design-vue'

import { useVbenForm } from '#/adapter/form'
import { againstSupply, approvalSupply, creatSupply, delSupply, editSupply, getBankList, getSupply,setDefaultRow } from '#/api/supply'

const emit = defineEmits(['refresh'])
const supply_id = ref(0)
const Posted = ref(0)

const inputDisabled = ref(true)

const baseOption = reactive({
  bankList: [], // 银行列表
})

// 获取银行列表
const fetchBankList = async () => {
  try {
    const res = await getBankList()
    baseOption.bankList = res
  } catch (error) {
    console.error('获取银行列表失败:', error)
  }
}

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-4/5',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'CustomRender',
      fieldName: '_divider',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: 'Input',
      fieldName: 'Supplyid',
      label: '供应商编码',
      componentProps: {
        disabled: true,
        placeholder: '后台自动生成',
      },
    },
    {
      component: 'Input',
      fieldName: 'SupplyNa',
      label: '供应商简称',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入供应商简称',
      },
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'SupplyName',
      label: '供应商全称',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入供应商全称',
      },
      rules: 'required',
    },
    {
      component: 'Select',
      fieldName: 'Xingzhi',
      label: '性质',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请选择性质',
        options: [
          { label: '通用', value: '通用' },
          { label: '物料', value: '物料' },
          { label: '加工厂', value: '加工厂' },
        ],
      },
    },
    {
      component: 'Input',
      fieldName: 'Leibie',
      label: '类别',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入类别',
      },
    },
    {
      component: 'Input',
      fieldName: 'UserSupplygroup',
      label: '权限分组',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入权限分组',
      },
    },
    {
      component: 'Input',
      fieldName: 'legal_person',
      label: '法人',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入法人',
      },
    },
    {
      component: 'Input',
      fieldName: 'Supplyman1',
      label: '联系人1',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入联系人1',
      },
    },
    {
      component: 'Input',
      fieldName: 'Supplytel1',
      label: '手机号1',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入手机号1',
      },
    },
    {
      component: 'Input',
      fieldName: 'Supplyadd',
      label: '地址',
      formItemClass: 'col-span-2',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入地址',
      },
    },
    {
      component: 'Switch',
      fieldName: 'Istaxrate',
      label: '含税',
      componentProps: {
        disabled: inputDisabled,
        class: 'w-[50px]',
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'Taxrate',
      label: '税率',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入税率',
        step: 1,
      },
    },
    {
      component: 'Input',
      fieldName: 'Gendan',
      label: '跟单',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入跟单',
      },
    },
    {
      component: 'Input',
      fieldName: 'Paytype',
      label: '付款方式',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入付款方式',
      },
    },
    {
      component: 'Input',
      fieldName: 'Brand',
      label: '品牌',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入品牌',
      },
    },
    {
      component: 'Input',
      fieldName: 'Email1',
      label: '邮箱1',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入邮箱1',
      },
    },
    {
      component: 'Input',
      fieldName: 'Supplyman2',
      label: '联系人2',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入联系人2',
      },
    },
    {
      component: 'Input',
      fieldName: 'Supplytel2',
      label: '手机号2',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入手机号2',
      },
    },
    {
      component: 'Input',
      fieldName: 'Supplyphone1',
      label: '电话1',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入电话1',
      },
    },
    {
      component: 'Input',
      fieldName: 'zhiwei1',
      label: '职位1',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入职位1',
      },
    },
    {
      component: 'Input',
      fieldName: 'Supplyfax',
      label: '传真',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入传真',
      },
    },
    {
      component: 'Textarea',
      fieldName: 'Remark',
      label: '备注',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入备注',
        rows: 4,
      },
    },

    {
      component: '_divider1',
      fieldName: '_divider1',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: 'CustomRender',
      fieldName: '_tabs',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
  ],
  wrapperClass: 'grid-cols-3',
})
const rowid =ref(0)
const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  fullscreen: true,
  appendToMain: true,
  fullscreenButton: false,
  onCancel() {
    modalApi.close()
    emit('refresh')
  },
  onConfirm: async () => {
    await baseFormApi.validateAndSubmitForm()
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { rowData, view } = modalApi.getData<Record<string, any>>()
      if (view === 'add') {
        inputDisabled.value = false
      } else if (view === 'edit') {
        inputDisabled.value = true
        rowid.value = rowData
        initData()

      }

      await fetchBankList()
    }
  },
})

async function initData() {
  getSupply({ id:rowid.value.id }).then((response) => {
    baseFormApi.setValues(response.row, false)
    bank_list.value = response.row.bank_list
    supply_id.value = response.row.id
    Posted.value = response.row.Posted
  })
}

const bank_list = ref([])
// 添加银行账户
async function addBank() {
  bank_list.value.push({
    supply_id: 0,
    bank_code: '',
    bank_name: '',
    bank_agency: '',
    user_name: '',
    bank_account: '',
    is_default: 0,
  })
}

// 删除银行账户
const supHandleDel = (index: number) => {
  bank_list.value.splice(index, 1)
}

// 设置默认银行账户
const setDefault = (record: any) => {
  setDefaultRow({ ...record, supply_id: rowid.value }).then(async (res: any) => {
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
    await initData()
    message.success(res.data.msg)
    emit('refresh')
  })
}

// 审核
const handleApproval = async () => {
  try {
    const res = await approvalSupply({ ids: [supply_id.value] })
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
    await initData()
    message.success(res.data.msg)
    emit('refresh')
  } catch {
    message.error('审核失败，请重试')
  }
}

// 反审
const handleAgainst = async () => {
  try {
    const res = await againstSupply({ ids: [supply_id.value] })
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
      await initData()
    message.success(res.data.msg)
    emit('refresh')
  } catch {
    message.error('反审核失败，请重试')
  }
}

// 删除
const handleDel = async () => {
  AntModal.confirm({
    title: '确认删除',
    content: '确定要删除该供应商吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        const res = await delSupply({ ids: [supply_id.value] })
        if (res.code !== 1) {
          message.error(res.msg)
          return
        }
        message.success('删除成功')
        modalApi.close()
        emit('refresh')
      } catch {
        message.error('删除失败，请重试')
      }
    },
  })
}

// 修改
const changeToSave = () => {
  inputDisabled.value = false
}

// 保存
async function save() {
  // 验证表单基础信息
  const { valid } = await baseFormApi.validate()
  if (!valid) return

  // 验证银行列表至少有一个
  if (!bank_list.value || bank_list.value.length === 0) {
    message.error('请至少添加一个银行账户')
    return
  }

  // 验证每行银行账户的必填字段
  for (let i = 0; i < bank_list.value.length; i++) {
    const bank = bank_list.value[i]

    // 户名必填
    if (!bank.user_name || bank.user_name.trim() === '') {
      message.error(`第${i + 1}行银行账户：户名为必填项`)
      return
    }

    // 银行账号必填
    if (!bank.bank_account || bank.bank_account.trim() === '') {
      message.error(`第${i + 1}行银行账户：银行账号为必填项`)
      return
    }

    // 银行名称必填
    if (!bank.bank_name || bank.bank_name.trim() === '') {
      message.error(`第${i + 1}行银行账户：银行名称为必填项`)
      return
    }

    // 银行代码必填
    if (!bank.bank_code || bank.bank_code.trim() === '') {
      message.error(`第${i + 1}行银行账户：银行代码为必填项`)
      return
    }

    // 开户行必填
    if (!bank.bank_agency || bank.bank_agency.trim() === '') {
      message.error(`第${i + 1}行银行账户：开行为必填项`)
      return
    }
  }
  const values = await baseFormApi.getValues()
  const parmas = {
    ...values,
    bank_list: bank_list.value,
  }
  if (values.id) {
    editSupply(parmas).then((res: any) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
        emit('refresh')
      } else {
        message.error(res.data.msg)
      }
    })
  } else {
    creatSupply(parmas).then((res: any) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
        emit('refresh')
      } else {
        message.error(res.data.msg)
      }
    })
  }

  // 这里可以添加后续的保存逻辑
}
</script>

<template>
  <Modal :title="inputDisabled ? '编辑供应商' : '新建供应商'">
    <BaseForm>
      <template #_divider>
        <Divider orientation="left">基础信息</Divider>
      </template>
      <template #_divider1>
        <Divider orientation="left">财务信息</Divider>
      </template>
      <template #_tabs>
        <div style="width: 100%">
          <Button type="primary" size="small" @click="addBank" :disabled="inputDisabled"> 添加 </Button>

          <Table :data-source="bank_list" bordered style="width: 100%" :scroll="{ x: 1200 }" :pagination="false">
            <TableColumn title="户名" data-index="user_name" key="user_name" width="150">
              <template #default="{ text, record, index }">
                <Input v-model:value="record.user_name" placeholder="请输入户名" :disabled="inputDisabled" />
              </template>
            </TableColumn>

            <TableColumn title="银行账号" data-index="bank_account" key="bank_account" width="180">
              <template #default="{ text, record, index }">
                <Input v-model:value="record.bank_account" placeholder="请输入银行账号" :disabled="inputDisabled" />
              </template>
            </TableColumn>

            <TableColumn title="银行名称" data-index="bank_name" key="bank_name" width="150">
              <template #default="{ text, record, index }">
                <Select v-model:value="record.bank_name" placeholder="请选择银行名称" :disabled="inputDisabled" show-search style="width: 200px">
                  <Select.Option v-for="item in baseOption.bankList" :key="item" :value="item">
                    {{ item }}
                  </Select.Option>
                </Select>
              </template>
            </TableColumn>

            <TableColumn title="银行代码" data-index="bank_code" key="bank_code" width="120">
              <template #default="{ text, record, index }">
                <Input v-model:value="record.bank_code" placeholder="请输入银行代码" :disabled="inputDisabled" />
              </template>
            </TableColumn>

            <TableColumn title="开户行" data-index="bank_agency" key="bank_agency" width="200">
              <template #default="{ text, record, index }">
                <Input v-model:value="record.bank_agency" placeholder="请输入开户行" :disabled="inputDisabled" />
              </template>
            </TableColumn>

            <TableColumn title="默认" data-index="is_default" key="is_default" width="80">
              <template #default="{ text, record, index }">
                <span :class="record.is_default === 1 ? 'text-green-600' : 'text-red-600'">
                  {{ record.is_default === 1 ? '是' : '否' }}
                </span>
              </template>
            </TableColumn>

            <TableColumn title="操作" key="action" width="300">
              <template #default="{ text, record, index }">
                <Space>
                  <Button size="small" danger @click="supHandleDel(index)" :disabled="inputDisabled"> 删除 </Button>
                  <Button type="primary" v-if="record.is_default === 0" size="small" @click="setDefault(record)"> 设置为默认 </Button>
                </Space>
              </template>
            </TableColumn>
          </Table>
        </div>
      </template>
    </BaseForm>
    <template #footer>
      <div class="flex justify-end">
        <Space>
          <Button @click="modalApi.close()">取消</Button>
          <Button v-if="!inputDisabled" type="primary" @click="save()"> 保存 </Button>
          <Button v-if="supply_id > 0 && Posted === 0 && inputDisabled" type="primary" danger @click="handleApproval"> 审核 </Button>
          <Button v-if="supply_id > 0 && Posted > 0 && inputDisabled" type="primary" danger @click="handleAgainst"> 反审 </Button>
          <Button v-if="supply_id > 0 && Posted === 0 && inputDisabled" type="primary" danger @click="handleDel"> 删除 </Button>
          <Button v-if="supply_id > 0 && Posted === 0 && inputDisabled" type="primary" @click="changeToSave"> 修改 </Button>
        </Space>
      </div>
    </template>
  </Modal>
</template>

<style scoped>
.fina-box {
  padding: 10px 0;
}
.fina-btn {
  margin-bottom: 16px;
}
</style>
